package com.micheal.spring.servlet;


import com.micheal.spring.annotation.Autowired;
import com.micheal.spring.annotation.Controller;
import com.micheal.spring.annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by micheal on 2018/4/19/0019.
 */
public class DispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String,Object> iocMap = new ConcurrentHashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        System.out.println("开始调用DispatherServlet.doPost()方法...");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化：定位、加载、注册

        //定位
        doLocationResource(config.getInitParameter("contextConfigLocation"));

        //加载
        doScanner(contextConfig.getProperty("scanPackage"));

        //注册
        doRegister();

        //依赖注入
        doAutowired();
    }

    private void doAutowired() {
        if(iocMap.isEmpty()){
            return;
        }

        for(Map.Entry<String, Object> entry : iocMap.entrySet()){
            Field[] declaredFields = entry.getClass().getDeclaredFields();
            for(Field field : declaredFields){
                if(!field.isAnnotationPresent(Autowired.class)){
                    continue;
                }
                Autowired autowired = field.getAnnotation(Autowired.class);
                String beanName = autowired.value().trim();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), iocMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doRegister() {
        if(classNames.isEmpty()){
            return;
        }

        try {
            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(Controller.class)){
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    iocMap.put(beanName, clazz.newInstance());
                }else if(clazz.isAnnotationPresent(Service.class)){
                    Service service = clazz.getAnnotation(Service.class);
                    String beanName = service.value();
                    if("".equals(beanName.trim())){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    iocMap.put(beanName, instance);

                    Class<?>[] interfaces = clazz.getInterfaces();
                    for(Class<?> intf : interfaces){
                        iocMap.put(intf.getName(), instance);
                    }
                }else{
                    continue;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫描类
     * @param scanPackage
     */
    private void doScanner(String scanPackage) {
        URL resource = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File dirFile = new File(resource.getFile());
        for(File file : dirFile.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage+"."+file.getName());
            }else{
                classNames.add(scanPackage+"."+file.getName().replace(".class",""));
            }
        }

    }

    /**
     * 定位资源文件
     * @param contextConfigLocation
     */
    private void doLocationResource(String contextConfigLocation) {

        InputStream resourceAsStream = this.getClass().getClassLoader()
                .getResourceAsStream(contextConfigLocation.replace("classpath:", ""));

        try {
            contextConfig.load(resourceAsStream);
        } catch (IOException e) {
            System.out.println("加载资源配置文件出错!");
            e.printStackTrace();
        }finally{
            if(resourceAsStream!=null){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String lowerFirstCase(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
